<?php


namespace App\Services\Tools;


use App\Exceptions\BasicException;
use App\Repositories\LogRepository;
use Illuminate\Support\Facades\Log;

class GuoGuangService
{
    // 域名网关 支付请求地址
    private $urls;
    // 支付公共接口
    private $payURL;
    // 统一收单线下交易查询
    private $queryURL;
    // 买家黑名单查询
    private $blacklistURL;

    const TYPE = [
        'ali' => "1", 'wechat' => "2"
    ];

    public function __construct()
    {
        $this->urls = 'https://openapi.cibn.cc';
        $this->payURL = '/api/v2/pay/order-create';
//        $this->queryURL = '/apiv2/payment/tradeQuery';
//        $this->blacklistURL = '/apiv2/payment/buyerIdBlackQuery';
        $this->merchantSubject = '鲸语';
    }

    /**
     * @param $orderSn
     * @param $money
     * @param $business_id
     * @param $param
     * @param $userIp
     * 掉漆支付
     * @param $user_id
     * @return array|bool|string
     * @throws BasicException
     */

    public function AliPay($orderSn, $money, $param, $userIp, $user_id,$business_id)
    {
        $data = [
            "mchOrderNo" => $orderSn,          //支付渠道1支付宝2微信
            "productCode" => 'ALI_APP',          //支付渠道1支付宝2微信
            "amount" => $money,          //支付渠道1支付宝2微信
            "currency" => 'cny',          //支付渠道1支付宝2微信
            "clientIp" => $userIp,          //支付渠道1支付宝2微信
            "subject" => $this->merchantSubject,          //支付渠道1支付宝2微信
            "notifyUrl" => $param['notify'],          //支付渠道1支付宝2微信
            "expiredTime" => '300',          //支付渠道1支付宝2微信
            "disablePayChannels" => "pcredit,creditCard",
            "body" => json_encode([
                'business_id' => $business_id
            ]),
        ];
        $result = $this->createOrder($data, $param['merchantID'], $param['md5Key']);

        if ($result['code'] != 200) {
            $logRtx = new LogRepository("gouguang-pay");
            $logRtx->log("pay_bug::", json_encode($result));
            $logRtx->File();
            throw new BasicException(-1, $result['msg']);
        }
        return $result['data']['payData'];
    }

    /**
     * 创建订单
     * @param array $orderParams
     * @param $mch_no
     * @param $key
     * @return mixed
     */
    public function createOrder($orderParams, $mch_no, $key)
    {
        $publicParams = [
            'mchNo' => $mch_no,
            'reqTime' => (string)round(microtime(true) * 1000),
            "currency" => "cny",
            'signType' => 'MD5',
            'version' => '1.0'
        ];
        $allParams = array_merge($publicParams, $orderParams);
        $allParams['sign'] = $this->generateSign($allParams, $key);
        return $this->get_curl_request($this->urls . $this->payURL, $allParams);
    }

    /**
     * 生成签名
     * @param array $params
     * @param $key
     * @return string
     */
    private function generateSign($params, $key)
    {
        ksort($params);
        $signStr = implode('&', array_map(
                function ($k, $v) {
                    return $k . '=' . $v;
                },
                array_keys($params),
                $params
            )) . $key;
        return md5($signStr);
    }
    public static function generateSignCheck($params, $key){
        unset($params['sign']);
        ksort($params);
        $signStr = implode('&', array_map(
                function ($k, $v) {
                    return $k . '=' . $v;
                },
                array_keys($params),
                $params
            )) . $key;
        return md5($signStr);
    }

    private function get_curl_request($url, $params)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($params));//请求数据json_encode
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Content-Type: application/json; charset=utf-8'
        ]); // 设置请求头  'Content-Type: application/json; charset=utf-8'
        $response = curl_exec($ch);
//        $logRtx = new LogRepository("gouguang-pay");
//        $logRtx->log("pay::", $response);
//        $logRtx->File();
        curl_close($ch);
        return json_decode($response, true);
    }


}
